package com.management.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.management.demo.domain.mall.PmsCategory;
import com.management.demo.mapper.mall.PmsCategoryMapper;
import com.management.demo.service.PmsCategoryService;
import com.management.demo.vo.mall.PmsCategoryVO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author Administrator
 * @description 针对表【pms_category】的数据库操作Service实现
 * @createDate 2025-06-18 10:59:32
 */
@Service
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryMapper, PmsCategory> implements PmsCategoryService {

    @Override
    public List<PmsCategoryVO> listWithTree() {
        // 查出所有分类
        List<PmsCategory> allCategoryList = list();
        List<PmsCategoryVO> allCategoryVOList = BeanUtil.copyToList(allCategoryList, PmsCategoryVO.class);

        // 组装成父子的树形结构
        // 找到所有的一级分类
        return allCategoryVOList.stream()
                .filter(item -> item.getParentCid().equals(0L))
                // 进行递归调用
                .peek(item -> item.setChildren(getChildren(item, allCategoryVOList)))
                .sorted(Comparator.comparingInt(PmsCategoryVO::getSort))
                .toList();
    }

    @Override
    public List<Long> findCategoryPath(Long categoryId) {
        List<Long> paths = new ArrayList<>();
        // 递归查询父类
        findParentPath(categoryId, paths);
        // 逆序，父在前
        Collections.reverse(paths);
        return paths;
    }

    private void findParentPath(Long categoryId, List<Long> paths) {
        paths.add(categoryId);
        PmsCategory pmsCategory = getById(categoryId);
        if (pmsCategory.getParentCid() != 0) {
            findParentPath(pmsCategory.getParentCid(), paths);
        }
    }

    /**
     * @param pmsCategoryVO     当前菜单
     * @param allCategoryVOList 所有菜单
     */
    private List<PmsCategoryVO> getChildren(PmsCategoryVO pmsCategoryVO, List<PmsCategoryVO> allCategoryVOList) {
        return allCategoryVOList.stream()
                .filter(item -> item.getParentCid().equals(pmsCategoryVO.getCatId()))
                .peek(item -> item.setChildren(getChildren(item, allCategoryVOList)))
                .sorted(Comparator.comparingInt(PmsCategoryVO::getSort))
                .toList();
    }
}




